﻿using Microsoft.OpenApi.Models;

namespace CoreWebApi.ProgramExtend
{
    /// <summary>
    /// Swagger启动项配置
    /// </summary>
    public static class AddSwaggerProgram
    {
        /// <summary>
        /// 注册Swagger服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="ProjectName"></param>
        public static void AddSwaggerAllocation(this IServiceCollection services, string ProjectName)
        {
            // 注册Swagger服务
            services.AddSwaggerGen(option =>
            {
                // 添加文档信息
                option.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Description = "API for SparkTodo",
                    Contact = new OpenApiContact()
                    {
                        Name = "GeekLiu",
                        Email = "809395347@qq.com"
                    }
                });

                // 包括文件
                option.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{ProjectName}.xml"), true);

                //api界面新增authorize按钮
                option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "请输入带有Bearer的Token",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Scheme = "bearer",
                    Type = SecuritySchemeType.Http,
                    BearerFormat = "JWT"
                });

                option.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {Type = ReferenceType.SecurityScheme, Id = "Bearer"}
                        },
                        new List<string>()
                    }
                });

                option.OrderActionsBy(o => o.RelativePath); // 对action的名称进行排序，如果有多个，就可以看见效果了。
            });
        }

        /// <summary>
        /// 启用Swagger服务
        /// </summary>
        /// <param name="application"></param>
        public static void UseSwaggerConfigure(this IApplicationBuilder application, string ProjectName)
        {
            //启用中间件以将生成的Swagger用作JSON端点。
            application.UseSwagger();

            //启用中间件以提供swagger-ui（HTML，JS，CSS等），并指定Swagger JSON端点
            application.UseSwaggerUI(option =>
            {
                option.SwaggerEndpoint("/swagger/v1/swagger.json", $"{ProjectName} V1");
                option.RoutePrefix = "swagger";//访问swagger的url地址名
                option.DocumentTitle = $"{ProjectName} API";

            });
        }

    }
}
